from tortoise import Tortoise, fields, run_async

from tortoise.models import Model
from tortoise import fields

class User(Model):
    id = fields.BigIntField(pk=True)
    username =  fields.CharField(max_length=255)
    password = fields.CharField(max_length=255)
    stores = fields.ReverseRelation["Store"]
    created_time = fields.DatetimeField(auto_now=True)
    
    def __str__(self) -> str:
        return self.username
   
class Store(Model):
    id = fields.BigIntField(pk=True)
    account =  fields.CharField(max_length=255)
    name =  fields.CharField(max_length=255)
    password =  fields.CharField(max_length=255)
    user = fields.ForeignKeyField("models.User", related_name="stores")
    created_time = fields.DatetimeField(auto_now=True)
    
    def __str__(self) -> str:
        return self.name
    

async def run():
    await Tortoise.init(db_url="sqlite://:memory:",
                        modules={"models": ["__main__"]}
    )
    await Tortoise.generate_schemas()
    
    
    user =  await User.create(username="user1", password="123")
    for i in range(5):
        store = await Store.create(account=f"store{i}", name=f"store{i}", password="123",user_id = user.id)
    for user in await User.all().prefetch_related("stores"):
        print(user)
        for store in user.stores:
            print(store.account)
 
    
 
if __name__ == "__main__":
    run_async(run())